﻿using System;
using System.Data;

namespace SdmxMl.SmsImportCfg
{
    /// <summary>
    /// Helper to create a dataset for info grouped all in same row via CR
    /// </summary>
    public class AllInOneRow
    {
        #region Internal Members

        private DataTable tbOneRow;
        private BaseCfg _cfg;
        private WorkSheetHelper ws;

        #endregion

        #region Properties

        public WorkSheetHelper WsHelper
        {
            get
            {
                // Split info to many rows
                PrepareOneRowTable();

                // Adjust Header to none
                _cfg.HeaderRowCount = 0;

                // Gives helper to work with
                return new WorkSheetHelper(tbOneRow);
            }
        }
        #endregion

        #region Constructor

        public AllInOneRow(BaseCfg cfg, DataTable dtWorksheet)
        {
            tbOneRow = dtWorksheet.Clone();
            _cfg = cfg;
            ws = new WorkSheetHelper(dtWorksheet);
        }
        #endregion

        #region Split Row
        /// <summary>
        /// Constrruct a datatable with splitted info (via Return char)
        /// </summary>
        private void PrepareOneRowTable()
        {
            if (_cfg.AllInOneRow == false)
                throw new ApplicationException("Invalid call for all in one row preparation.");
            
            // Get index of info row and parse all cells
            int targetRow = _cfg.HeaderRowCount + 1;
            for (int col = 1; col <= ws.ColCount; ++col)
            {
                // Fetch cell and separate newlines
                string[] arr = ws.GetCellContent(targetRow, col).Split('\n');

                // Update table row size
                if (tbOneRow.Rows.Count < arr.Length)
                    for (int r = tbOneRow.Rows.Count; r < arr.Length; r++)
                        tbOneRow.Rows.Add(tbOneRow.NewRow());

                // copy material
                for (int r = 0; r < arr.Length; r++)
                    tbOneRow.Rows[r][col - 1] = arr[r];
            }
        }
        #endregion
    }
}
